#!/usr/bin/env python
#coding=utf-8
'''
Created on Jul 22, 2010

@author: lxd
####todo将添加、删除、修改封装到类里
'''
import wx
from common.tools import Tools
import bin_login
import bin_register

class MainFrame(wx.Dialog):
    def __init__(self):
        wx.Dialog.__init__(self, None, -1, size=(500, -1), title=u'用户管理')
        self.palMain = panelUser(self)      
#        self.Center()        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        
    def OnClose(self, event):
        new_users = self.palMain.countUsers()
        users = Tools.loadData(r'db/user') 
        if new_users:       
            if (users and new_users != users) or not users: 
                dlg = wx.MessageDialog(None, u'用户管理已更改，要保存吗？', u'友情提示', wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
                retCode = dlg.ShowModal()    
                if retCode == wx.ID_YES:
                    Tools.saveData(r'db/user', new_users)
                    self.Destroy()
                elif retCode == wx.ID_NO:
                    self.Destroy()                    
            else:
                self.Destroy()                    
        else:
            self.Destroy()
                    
class panelUser(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent) 
        #ttooooooooooooooooooooooooodo加框线 
        self.createTop()  
        self.infoSizer = self.createInfoSizer()                 
        self.createBtn()      
        self.btnSizer = self.createBtnSizer() 
        self.lblMessage = wx.StaticText(self, -1, u"共0个小号")         
        self.LstrlContent = self.createLstrlContent()
        self.layout()
        
        self.Bind(wx.EVT_BUTTON, self.OnAddClick, self.btnAdd)   
        self.Bind(wx.EVT_BUTTON, self.OnEditClick, self.btnEdit) 
        self.Bind(wx.EVT_BUTTON, self.OnDelClick, self.btnDel)
        self.Bind(wx.EVT_BUTTON, self.OnSaveClick, self.btnSave)
        self.Bind(wx.EVT_BUTTON, self.OnFriendClick, self.btnFriend)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelect, self.LstrlContent)
        
        self.loadUserData()

    def createBtn(self):
        self.btnAdd = wx.Button(self, -1, u'添加')
        self.btnEdit = wx.Button(self, -1, u'修改')
        self.btnEdit.Enable(False)
        self.btnDel = wx.Button(self, -1, u'删除')
        self.btnDel.Enable(False)
        self.btnSave = wx.Button(self, -1, u'保存到数据库')
        self.btnFriend = wx.Button(self, -1, u'小号申请')

    def createTop(self):
        self.lblName = wx.StaticText(self, -1, u"用户名:")
        self.txtName = wx.TextCtrl(self, -1, "", size=(150, -1))
        self.lblPwd = wx.StaticText(self, -1, u"密码:")
        self.txtPwd = wx.TextCtrl(self, -1, "", size=(150, -1))
        self.txtName.SetFocus()
        
    def createInfoSizer(self):
        infoSizer = wx.BoxSizer(wx.HORIZONTAL)
        infoSizer.Add(self.lblName, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
        infoSizer.Add(self.txtName, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
        infoSizer.Add(self.lblPwd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
        infoSizer.Add(self.txtPwd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
        return infoSizer
    
    def createBtnSizer(self):
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(self.btnAdd, 0, wx.ALL, 5)
        btnSizer.Add(self.btnEdit, 0, wx.ALL, 5)
        btnSizer.Add(self.btnDel, 0, wx.ALL, 5)
        btnSizer.Add(self.btnSave, 0, wx.ALL, 5)
        btnSizer.Add(self.btnFriend, 0, wx.ALL, 5)
        return btnSizer
                
    def createLstrlContent(self):
        lstrlContent = wx.ListCtrl(self, -1, size=(360, -1), style=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES)
        lstrlContent.InsertColumn(0, u"用户名")
        lstrlContent.InsertColumn(1, u"密码")
        lstrlContent.SetColumnWidth(0, 175)
        lstrlContent.SetColumnWidth(1, 175)
        lstrlContent.SetItemCount(10)
        return lstrlContent
   
    def layout(self):
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(self.infoSizer, 0, wx.ALL | wx.EXPAND, 5)
        mainSizer.Add(self.btnSizer, 0, wx.ALL | wx.EXPAND, 5)
        mainSizer.Add(self.lblMessage, 0, wx.ALL, 5)
        mainSizer.Add(self.LstrlContent, 1, wx.ALL | wx.EXPAND, 5)
        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self) 
         
    ################################## 
    def afterModify(self):
        self.txtName.Clear()
        self.txtPwd.Clear() 
        self.txtName.SetFocus()        
        self.btnEdit.Enable(False)
        self.btnDel.Enable(False) 
        
    def hasExisted(self, name, lst): 
        for item in lst: 
            if name == item:
                wx.MessageBox(u'用户名已存在', u'友情提示', style=wx.OK | wx.ICON_EXCLAMATION)
                self.afterModify()
                return True
        return False  
              
    def hasBlank(self, name, pwd):  
        if name == '' or pwd == '':
            wx.MessageBox(u'用户名和密码不得为空', u'友情提示', style=wx.OK | wx.ICON_EXCLAMATION)
            self.afterModify()
            return True
        else:
            return False
                      
    def OnAddClick(self, event):
        name = self.txtName.GetValue().strip()
        pwd = self.txtPwd.GetValue().strip() 
        if not self.hasBlank(name, pwd):
            lst = []
            count = self.LstrlContent.GetItemCount()
            for i in range(count): 
                lst.append(self.LstrlContent.GetItem(i, 0).Text)
                     
            if not self.hasExisted(name, lst):
                index = self.LstrlContent.InsertStringItem(0, name)
                self.LstrlContent.SetStringItem(index, 1, pwd)
                self.afterModify() 
        
    def OnEditClick(self, event):         
        name = self.txtName.GetValue().strip()
        pwd = self.txtPwd.GetValue().strip()
        if not self.hasBlank(name, pwd):
            index = self.LstrlContent.GetFirstSelected()
            lst = []
            count = self.LstrlContent.GetItemCount()
            for i in range(count): 
                lst.append(self.LstrlContent.GetItem(i, 0).Text)
            lst.remove(self.LstrlContent.GetItem(index, 0).Text)
                                
            if not self.hasExisted(name, lst):
                self.LstrlContent.SetStringItem(index, 0, name) 
                self.LstrlContent.SetStringItem(index, 1, pwd)        
                self.afterModify() 
    
    def OnDelClick(self, event):
        index = self.LstrlContent.GetFirstSelected()
        self.LstrlContent.deleteItem(index)
        self.afterModify() 

    def OnSaveClick(self, event):
        users = self.countUsers()
        Tools.saveData(r'db/user', users)
        wx.MessageBox(u'保存成功', u'友情提示', style=wx.OK | wx.ICON_EXCLAMATION)

    #######申请小号###############
    def getRegisterInfo(self, inviteUrl):
        self.messageCall(u'正在输入注册信息') 
        dialog = bin_register.RegisterDialog(inviteUrl)
        dialog.LstrlContent = self.LstrlContent
        dialog.lblMessage = self.lblMessage
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            self.messageCall(u'小号申请成功') 
            return True
        else:
            self.messageCall(u'请输入注册信息') 
        dialog.Destroy()  
        return False
                
    def OnFriendClick(self, event):
        dialog = bin_login.MainLoginDialog()
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            if dialog.inviteUrl:
                while True:
                    register = self.getRegisterInfo(dialog.inviteUrl)
                    if not register:
                        break                    
            else:
                self.messageCall(u'未获取到邀请码，请先登录主号')            
        else:
            self.messageCall(u'请先登录主号') 
        dialog.Destroy()      

    def messageCall(self, msg):
        self.lblMessage.SetLabel(msg)
    
    ##################        
    def OnItemSelect(self, event):
        index = event.GetIndex()
        self.txtName.SetValue(self.LstrlContent.GetItem(index, 0).Text)
        self.txtPwd.SetValue(self.LstrlContent.GetItem(index, 1).Text)
        self.btnEdit.Enable(True)
        self.btnDel.Enable(True)
        
    def countUsers(self):
        users = []
        count = self.LstrlContent.GetItemCount()
        for i in range(count): 
            name = self.LstrlContent.GetItem(i, 0).Text
            pwd = self.LstrlContent.GetItem(i, 1).Text
            users.append(dict(name=name, pwd=pwd))        
        return users
    
    def loadUserData(self):
        users = Tools.loadData(r'db/user')
        if users:
            users.reverse()
            for user in users:
                index = self.LstrlContent.InsertStringItem(0, user['name'])
                self.LstrlContent.SetStringItem(index, 1, user['pwd'])  

                         
if __name__ == "__main__":
    app = wx.App()
    MainFrame().Show()
    app.MainLoop()
